//
//  UIImage+TYHelper.m
//  TYFoundation
//
//  Created by 郭艺伟 on 2019/2/28.
//

#import "UIImage+TYHelper.h"

#import "NSFileManager+TYHelper.h"

#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

static const CGFloat irregularFactor = 4.0;

@implementation UIImage (TYHelper)

+ (UIImage *)ty_imageFileNamed:(NSString *)name {
    if ([NSFileManager ty_isRetinaImageFileOnly:name]) {
        NSString *stringPath = [NSFileManager ty_imageFilePathByName:name isRetina:YES];
        NSData *dataImage = [NSData dataWithContentsOfFile:stringPath];
        UIImage *image = [UIImage imageWithData:dataImage];
        
        return [UIImage ty_scaleImage:image toScale:.5f];
    } else {
        NSString *fileExtension = name.pathExtension;
        NSString *fileName = name.stringByDeletingPathExtension;
        NSString *path = [[NSBundle mainBundle] pathForResource:fileName
                                                         ofType:fileExtension];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        BOOL bNeedScale = NO;
        //是否retina显示屏
        if ([UIScreen mainScreen].scale > 1.f) {
            NSString *retinaPath = [NSFileManager ty_imageFilePathByName:name isRetina:YES];
            if ([fm fileExistsAtPath:retinaPath]) {
                path = retinaPath;
                bNeedScale = YES;
            }
        }
        
        if ([fm fileExistsAtPath:path]) {
            //todo：使用imageWithContentsOfFile:方法会导致打开的文件句柄无法关闭，在ulimit限制比较小的条件下会引发后续部分文件无法打开
            //        UIImage* image = [UIImage imageWithContentsOfFile:sFile];
            NSData *dataImage = [NSData dataWithContentsOfFile:path];
            UIImage *image = [UIImage imageWithData:dataImage];
            if (bNeedScale) {
                image = [UIImage ty_scaleImage:image toScale:.5f];
            }
            return image;
        } else {
            return nil;
        }
    }
}

//UIImage等比缩放
+ (UIImage *)ty_scaleImage:(UIImage *)image toScale:(float)scaleSize {
    
    if([[UIScreen mainScreen] scale] > 1.0) {
        //高分辨率执行UIGraphicsBeginImageContextWithOptions按分辨率进行缩放，防止锯齿
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize), NO, [[UIScreen mainScreen] scale] );
    } else {
        UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    }
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

//UIImage重置大小
+ (UIImage *)ty_reSizeImage:(UIImage *)image toSize:(CGSize)reSize {
    
    if([[UIScreen mainScreen] scale] > 1.0) {
        //高分辨率执行UIGraphicsBeginImageContextWithOptions按分辨率进行缩放，防止锯齿
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(reSize.width, reSize.height), NO, [[UIScreen mainScreen] scale]);
    } else {
        UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));
    }
    
    [image drawInRect:CGRectMake(1, 1, reSize.width-2, reSize.height-2)];
    UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return reSizeImage;
}

//zhengkai自动适配各屏幕图片
+ (UIImage *)ty_imageWithFile:(NSString*)file {
    
    NSString *dstPath = file;
    NSString *imageMark = @"";
    if (file && [[UIScreen mainScreen] scale]) {
        if(SCREEN_HEIGHT == 568.0 && SCREEN_WIDTH == 320.0)
            imageMark = @"-568h@2x";
        else if(SCREEN_HEIGHT == 480.0 && SCREEN_WIDTH == 320.0)
            imageMark = @"@2x";
        
        NSRange range = [file rangeOfString:imageMark];
        if (range.location == NSNotFound) {
            NSString *retinaPath = [NSString stringWithFormat:@"%@%@.%@",
                                    [file stringByDeletingPathExtension], imageMark,[file pathExtension]];
            NSString *fullPath = [[NSBundle mainBundle] pathForResource:[retinaPath stringByDeletingPathExtension]
                                                                 ofType:[retinaPath pathExtension]];
            if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]){
                dstPath = fullPath;
            }
            else{
                dstPath = [[NSBundle mainBundle] pathForResource:[dstPath stringByDeletingPathExtension]
                                                          ofType:[dstPath pathExtension]];
            }
            
        }
    }
    
    return [UIImage imageWithContentsOfFile:dstPath];
}
@end


@implementation UIImage (tintColor)

- (UIImage *)ty_imageWithTintColor:(UIColor *)tintColor {
    return [self ty_imageWithTintColor:tintColor blendMode:kCGBlendModeDestinationIn];
}

- (UIImage *)ty_imageWithGradientTintColor:(UIColor *)tintColor {
    return [self ty_imageWithTintColor:tintColor blendMode:kCGBlendModeOverlay];
}

- (UIImage *)ty_imageWithTintColor:(UIColor *)tintColor blendMode:(CGBlendMode)blendMode {
    if (!tintColor) {
        return self;
    }
    
    //We want to keep alpha, set opaque to NO; Use 0.0f for scale to use the scale factor of the device’s main screen.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
    [tintColor setFill];
    CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
    UIRectFill(bounds);
    
    //Draw the tinted image in context
    [self drawInRect:bounds blendMode:blendMode alpha:1.0f];
    
    if (blendMode != kCGBlendModeDestinationIn) {
        [self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0f];
    }
    
    UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return tintedImage;
}
@end

@implementation UIImage (initWithUIColor)

+ (UIImage *)ty_imageWithColor:(UIColor *)color size:(CGSize)size {
    UIImage *img = nil;
    
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,
                                   color.CGColor);
    CGContextFillRect(context, rect);
    
    img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return img;
}
@end

@implementation UIImage (for_stretchable)

- (UIImage *)ty_stretchableImageWithCapInsets:(UIEdgeInsets)capInsets {
    
    //ios version >= 5.0
    if (&NSURLFileResourceIdentifierKey) {
        if (capInsets.bottom == 0 && capInsets.right == 0) {
            capInsets.bottom = self.size.height - (capInsets.top + 1);
            capInsets.right = self.size.width -( capInsets.left + 1);
        }
        return [self resizableImageWithCapInsets:capInsets];
    } else {
        return [self stretchableImageWithLeftCapWidth:capInsets.left topCapHeight:capInsets.top];
    }
}
@end

@implementation UIImage (Tint)

- (UIImage *)ty_imageWithColor:(UIColor*)color rect:(CGRect)rect level:(CGFloat)level {
    CGRect imageRect = CGRectMake(0.0f, 0.0f, self.size.width, self.size.height);
    
    UIGraphicsBeginImageContextWithOptions(imageRect.size, NO, self.scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    [self drawInRect:imageRect];
    
    CGContextSetFillColorWithColor(ctx, [color CGColor]);
    CGContextSetAlpha(ctx, level);
    CGContextSetBlendMode(ctx, kCGBlendModeSourceAtop);
    CGContextFillRect(ctx, rect);
    
    CGImageRef imageRef = CGBitmapContextCreateImage(ctx);
    UIImage *darkImage = [UIImage imageWithCGImage:imageRef
                                             scale:self.scale
                                       orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    
    UIGraphicsEndImageContext();
    
    return darkImage;
}
@end


@implementation UIImage (imageToSize)

/**
 *    将UIImage的尺寸放缩到指定的大小
 *    @param img UIImage对象
 *    @param targetSize 目标尺寸
 *
 **/
+ (UIImage *)ty_imageScaleToSize:(UIImage *)img size:(CGSize) targetSize{
    
    if([[UIScreen mainScreen] scale] > 1.0) {
        //高分辨率执行UIGraphicsBeginImageContextWithOptions按分辨率进行缩放，防止锯齿
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(targetSize.width, targetSize.height), NO, img.scale);
    } else {
        UIGraphicsBeginImageContext(CGSizeMake(targetSize.width, targetSize.height));
    }
    
    //UIGraphicsBeginImageContext(targetSize);
    
    [img drawInRect:CGRectMake(0.0,0.0,targetSize.width,targetSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

/**
 *    将UIImage的尺寸等比例放缩到指定的大小，并进行调整。
 *    @param img UIImage对象
 *    @param targetSize 目标尺寸
 *
 **/
+ (UIImage *)ty_imageScaleWithSameProportion:(UIImage *)image forSize:(CGSize)targetSize
{
    CGSize imageSize = image.size;
    
    if(CGSizeEqualToSize(imageSize,targetSize) == YES){
        return image;
    }
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat scaleWidth = targetSize.width;
    CGFloat scaleHeight = targetSize.height;
    
    
    if ( (0.0 == width)  || (0.0 == height) ) {
        return  image;
    }
    // 按宽高比，调整图片的压缩比例自动适应targetSize的宽高
    UIImage *newImage = nil;
    CGFloat widthFactor = scaleWidth / width;
    CGFloat heightFactor = scaleHeight / height;
    CGFloat scaleFactor = 0.0;
    
    if(widthFactor > heightFactor){
        scaleFactor = heightFactor;
    }else{
        scaleFactor = widthFactor;
    }
    
    CGFloat scaledWidth = width * scaleFactor;
    CGFloat scaledHeight = height * scaleFactor;
    CGSize target = CGSizeMake(scaledWidth,scaledHeight);
    
    UIGraphicsBeginImageContext(target);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [image drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    if(newImage != nil){
        return newImage;
    }else{
        return image;
    }
}

/**
 *    将UIImage从顶部按指定窗口裁剪
 *    @param img UIImage对象
 *    @param targetSize 目标窗口尺寸
 *
 **/
+ (UIImage *)ty_imageScaleCut:(UIImage *)image size:(CGSize)targetSize{
    CGSize imageSize = image.size;
    if ((imageSize.width < targetSize.width) || (imageSize.height < targetSize.height) ) {
        NSLog(@"In UIImage+TYHelper '+ (UIImage *)imageScaleCut:(UIImage *)image size:(CGSize)targetSize' targetsize is larger than image !");
        return image;
    }
    CGFloat height = 0.0;
    CGFloat width = 0.0;
    
    CGRect newImageRect = CGRectMake(width, height, targetSize.width, targetSize.height);
    UIImage *newImage = image;
    CGImageRef imageRef = newImage.CGImage;
    CGImageRef subImage = CGImageCreateWithImageInRect(imageRef, newImageRect);
    
    UIImage *imageCut = [UIImage imageWithCGImage:subImage];
    CGImageRelease(subImage);
    return imageCut;
    
}

/**
 *    将UIImage的字节数压缩的一定的要求
 *    @param img UIImage对象
 *    @param ttargetFileBytes 目标字节数
 *
 **/
+ (UIImage *)ty_imageCompress:(UIImage *)image imageFileSize:(NSInteger)targetFileBytes{
    NSData *imageDataSizeTest = [[NSData alloc] init];
    float qualityFactor = 1.0;
    
    while (qualityFactor >= 0.0) {
        if(UIImageJPEGRepresentation(image, qualityFactor).length <= targetFileBytes){
            imageDataSizeTest = UIImageJPEGRepresentation(image, qualityFactor);
            break;
        }
        
        qualityFactor -= 0.02;
        //如果压缩达不到要求的比特数则返回原图
        if (qualityFactor < 0.0) {
            NSLog(@"In UIImage+TYHelper '+(UIImage *)imageCompress1:(UIImage *)image imageFileSize:(NSInteger)targetFileBytes' could not compress to targetFileBytes!");
            imageDataSizeTest = nil;
            return image;
        }
    }
    
    UIImage *newImage = [UIImage imageWithData:imageDataSizeTest];
    imageDataSizeTest = nil;
    
    return newImage;
}

@end

@implementation UIImage (imageForDifferentApplication)

- (UIImage *)ty_scaleImageForScenes:(TYImageCompressType)scaleOption {
    switch (scaleOption) {
        case TYImageCompressTypeAvatarOrigin:
            return [self ty_TYImageCompressTypeAvatarOrigin];
        case TYImageCompressTypeAvatarThumbnail:
            return [self ty_TYImageCompressTypeAvatarThumbnail];
        case TYImageCompressTypeWeiboAndIMOrigin:
            return [self ty_TYImageCompressTypeWeiboAndIMOrigin];
        case TYImageCompressTypeWeiboAndIMThumbnail:
            return [self ty_TYImageCompressTypeWeiboAndIMThumbnail];
        case TYImageCompressTypePanorama:
            return [self ty_imageCompressForPanorama];
        default:
            return self;
    }
}

/**
 *    处理微博缩略图的方法
 **/
- (UIImage *)ty_imageScaleForBlog{
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    float MaxScale = 240/70;
    
    if ((0.0 == imageSize.width ) || (0.0 == imageSize.height) ) {
        return  self;
    }
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
    }
    
    if ((longerEdge <= 240)) {
        return self;
    }
    
    if ((longerEdge/shorterEdge >= 1)&&(longerEdge/shorterEdge <= MaxScale)) {
        CGSize newSize = CGSizeMake(240.0, 240.0);
        UIImage *newImage = [UIImage ty_imageScaleWithSameProportion:self forSize:newSize];
        return  newImage;
    }
    
    if (longerEdge/shorterEdge > MaxScale) {
        CGSize zoomSize = CGSizeMake(70.0, 70.0*longerEdge/shorterEdge);
        UIImage *zoomImage = [UIImage ty_imageScaleWithSameProportion:self forSize:zoomSize];
        CGSize cutSize = CGSizeMake(70.0, 240.0);
        UIImage *newImage = [UIImage ty_imageScaleCut:zoomImage size:cutSize];
        return newImage;
    }
    
    return self;
}

/**
 *    将图片尺寸压缩至640x640并将图片字节数也进行一定压缩用于91U头像
 **/
- (UIImage *)ty_TYImageCompressTypeAvatarOrigin{
    CGSize imageSize = self.size;
    float qualityFactor = compressQualityFactor; //统计显示，压缩质量系数在0.51时能保证图片的质量和较高的压缩率。
    CGSize sizeForScale = CGSizeMake(640.0, 640.0);
    float scaleFactor = imageSize.width*imageSize.height/640.0/640.0;
    // 依据图片的裁剪情况，调整压缩质量系数
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    UIImage *newImageForScale =[UIImage ty_imageScaleToSize:self size:sizeForScale];
    
    NSData *newImageData  = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
    
    UIImage *newImage = [UIImage imageWithData:newImageData];
    
    if(newImage != nil){
        return newImage;
    }else{
        return self;
    }
    
}

/**
 *    将图片尺寸压缩至140x140并将图片字节数也进行一定压缩用于91U小头像
 **/
- (UIImage *)ty_TYImageCompressTypeAvatarThumbnail{
    CGSize imageSize = self.size;
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(140.0, 140.0);
    float scaleFactor = imageSize.width*imageSize.height/140.0/140.0;
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    UIImage *newImageForScale =[UIImage ty_imageScaleToSize:self size:sizeForScale];
    
    NSData *newImageData  = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
    
    UIImage *newImage = [UIImage imageWithData:newImageData];
    
    if(newImage != nil){
        return newImage;
    }else{
        return self;
    }
    
}

/**
 *    将图片尺寸等比压缩至长边960并将图片字节数也进行一定压缩用于微博和IM
 **/
- (UIImage *)ty_TYImageCompressTypeWeiboAndIMOrigin{
    
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
    }
    
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(960.0, 960.0);
    float scaleFactor = 1.0;
    
    if (imageSize.width > imageSize.height) {
        scaleFactor = imageSize.width*imageSize.width/960.0/960.0;
    }else{
        scaleFactor = imageSize.height*imageSize.height/960.0/960.0;
    }
    
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    if (longerEdge / shorterEdge >= irregularFactor) {
        if (imageSize.width * imageSize.height > 960.0*960.0) {
            qualityFactor = 0.4 * 960.0 * 960.0 / imageSize.width / imageSize.height;
        }else{
            qualityFactor = 0.4;
        }
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImage;
    }
    else if (longerEdge >= 960.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImage;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return  newImage;
    }
}

/**
 *    将图片尺寸等比压缩至长边200并将图片字节数也进行一定压缩用于微博和IM
 **/
- (UIImage *)ty_TYImageCompressTypeWeiboAndIMThumbnail{
    CGSize imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    CGSize sizeForCut;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
        sizeForCut = CGSizeMake(imageSize.width, imageSize.width*3);
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
        sizeForCut = CGSizeMake(imageSize.height*3, imageSize.height);
    }
    
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(200.0, 200.0);
    CGSize zoomSize = CGSizeMake(198.0, 198.0);
    float scaleFactor = 1.0;
    
    if (imageSize.width > imageSize.height) {
        scaleFactor = imageSize.width*imageSize.width/200.0/200.0;
    }else{
        scaleFactor = imageSize.height*imageSize.height/200.0/200.0;
    }
    
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    if (longerEdge / shorterEdge >= irregularFactor) {
        UIImage *zoomImage = [UIImage ty_imageScaleCut:self size:sizeForCut];
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:zoomImage forSize:zoomSize];
        NSData *newImageData =UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImage;
    }
    else if (longerEdge >= 200.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImage;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return  newImage;
    }
    
}

/**
 *    将图片尺寸等比压缩并将图片字节数也进行一定压缩用于微博长图显示
 **/
- (UIImage *)ty_imageCompressForLongImageWithEdgeSame{
    float qualityFactor = compressQualityFactor;
    
    NSData *newImageData = UIImageJPEGRepresentation(self, qualityFactor);
    
    UIImage *newImage = [UIImage imageWithData:newImageData];
    
    if(newImage != nil){
        return newImage;
    }else{
        return self;
    }
}

/**
 *    将图片尺寸等比压缩至66x198并将图片字节数也进行一定压缩用于微博长图显示
 **/
- (UIImage *)ty_imageCompressForLongImageWithEdge66x198{
    CGSize imageSize = self.size;
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(66.0, 198.0);
    float scaleFactor = imageSize.width*imageSize.height/66.0/198.0;
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    UIImage *newImageForScale =[UIImage ty_imageScaleToSize:self size:sizeForScale];
    
    NSData *newImageData  = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
    
    UIImage *newImage = [UIImage imageWithData:newImageData];
    
    if(newImage != nil){
        return newImage;
    }else{
        return self;
    }
}
/**
 *  全景图压缩
 *
 *  @return image
 */
-(UIImage *)ty_imageCompressForPanorama{
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    //    CGFloat shorterEdge;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        //        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        //        shorterEdge = imageSize.height;
    }
    
    //    float qualityFactor = 0.75;
    CGSize sizeForScale = CGSizeMake(2048, 2048);
    //    float scaleFactor = 1.0;
    //
    //    if (imageSize.width > imageSize.height) {
    //        scaleFactor = imageSize.width*imageSize.width/2048/2048;
    //    }else{
    //        scaleFactor = imageSize.height*imageSize.height/2048/2048;
    //    }
    
    //    if (scaleFactor < 1.0) {
    //        qualityFactor = qualityFactor * sqrt(scaleFactor);
    //    }
    
    if (longerEdge >= 2048.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, 0.51);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImage;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, 0.51);
        UIImage *newImage = [UIImage imageWithData:newImageData];
        return  newImage;
    }
    
}

/**
 *    中图显示应用，使尺寸图片适应于对应的控件尺寸。
 *    @param image UIImage对象
 *    @param targetSize 目标控件尺寸
 **/
- (UIImage *)ty_imageMiddlePresent:(CGSize)targetSize{
    CGSize imageSize = self.size;
    
    if ((imageSize.width < 0.5*targetSize.width) && (imageSize.height < 0.5*targetSize.height)) {
        return self;
    }else{
        UIImage *newImage = [UIImage ty_imageScaleWithSameProportion:self forSize:targetSize];
        return  newImage;
    }
}

- (NSData *)ty_dataWithScaledImageForScenes:(TYImageCompressType)scaleOption{
    switch (scaleOption) {
        case TYImageCompressTypeAvatarOrigin:
            return [self dataWithMUPImageCompressTypeAvatarOrigin];
        case TYImageCompressTypeAvatarThumbnail:
            return [self dataWithMUPImageCompressTypeAvatarThumbnail];
        case TYImageCompressTypeWeiboAndIMOrigin:
            return [self dataWithMUPImageCompressTypeWeiboAndIMOrigin];
        case TYImageCompressTypeWeiboAndIMThumbnail:
            return [self dataWithMUPImageCompressTypeWeiboAndIMThumbnail];
        case TYImageCompressTypePanorama:
            return [self ty_dataWithImageCompressForPanorama];
        default:
            return nil;
    }
}

- (NSData *)dataWithImageScaleForBlog{
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    float MaxScale = 240/70;
    NSData *newImageData;
    
    if ((0.0 == imageSize.width ) || (0.0 == imageSize.height) ) {
        newImageData = UIImageJPEGRepresentation(self,compressQualityFactor);
        return  newImageData;
    }
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
    }
    
    if ((longerEdge <= 240)) {
        newImageData = UIImageJPEGRepresentation(self,compressQualityFactor);
        return  newImageData;
    }
    
    if ((longerEdge/shorterEdge >= 1)&&(longerEdge/shorterEdge <= MaxScale)) {
        CGSize newSize = CGSizeMake(240.0, 240.0);
        UIImage *newImage = [UIImage ty_imageScaleWithSameProportion:self forSize:newSize];
        newImageData = UIImageJPEGRepresentation(newImage,compressQualityFactor);
        return  newImageData;
    }
    
    if (longerEdge/shorterEdge > MaxScale) {
        CGSize zoomSize = CGSizeMake(70.0, 70.0*longerEdge/shorterEdge);
        UIImage *zoomImage = [UIImage ty_imageScaleWithSameProportion:self forSize:zoomSize];
        CGSize cutSize = CGSizeMake(70.0, 240.0);
        UIImage *newImage = [UIImage ty_imageScaleCut:zoomImage size:cutSize];
        newImageData = UIImageJPEGRepresentation(newImage,compressQualityFactor);
        return  newImageData;
    }
    
    newImageData = UIImageJPEGRepresentation(self,compressQualityFactor);
    return  newImageData;
}

- (NSData *)dataWithMUPImageCompressTypeAvatarOrigin{
    CGSize imageSize = self.size;
    float qualityFactor = compressQualityFactor; //统计显示，压缩质量系数在0.51时能保证图片的质量和较高的压缩率。
    CGSize sizeForScale = CGSizeMake(640.0, 640.0);
    float scaleFactor = imageSize.width*imageSize.height/640.0/640.0;
    // 依据图片的裁剪情况，调整压缩质量系数
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    UIImage *newImageForScale =[UIImage ty_imageScaleToSize:self size:sizeForScale];
    
    NSData *newImageData  = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
    
    return newImageData;
}

- (NSData *)dataWithMUPImageCompressTypeAvatarThumbnail{
    CGSize imageSize = self.size;
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(140.0, 140.0);
    float scaleFactor = imageSize.width*imageSize.height/140.0/140.0;
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    UIImage *newImageForScale =[UIImage ty_imageScaleToSize:self size:sizeForScale];
    
    NSData *newImageData  = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
    
    return newImageData;
}

- (NSData *)dataWithMUPImageCompressTypeWeiboAndIMOrigin{
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
    }
    
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(960.0, 960.0);
    float scaleFactor = 1.0;
    
    if (imageSize.width > imageSize.height) {
        scaleFactor = imageSize.width*imageSize.width/960.0/960.0;
    }else{
        scaleFactor = imageSize.height*imageSize.height/960.0/960.0;
    }
    
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    if (longerEdge / shorterEdge >= irregularFactor) {
        if (imageSize.width * imageSize.height > 960.0*960.0) {
            qualityFactor = 0.4 * 960.0 * 960.0 / imageSize.width / imageSize.height;
        }else{
            qualityFactor = 0.4;
        }
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        return newImageData;
    }
    else if (longerEdge >= 960.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        return newImageData;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        return  newImageData;
    }
    
}

- (NSData *)dataWithMUPImageCompressTypeWeiboAndIMThumbnail{
    CGSize imageSize = self.size;
    CGFloat longerEdge;
    CGFloat shorterEdge;
    CGSize sizeForCut;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        shorterEdge = imageSize.width;
        sizeForCut = CGSizeMake(imageSize.width, imageSize.width*3);
    }else{
        longerEdge = imageSize.width;
        shorterEdge = imageSize.height;
        sizeForCut = CGSizeMake(imageSize.height*3, imageSize.height);
    }
    
    float qualityFactor = compressQualityFactor;
    CGSize sizeForScale = CGSizeMake(200.0, 200.0);
    CGSize zoomSize = CGSizeMake(198.0, 198.0);
    float scaleFactor = 1.0;
    
    if (imageSize.width > imageSize.height) {
        scaleFactor = imageSize.width*imageSize.width/200.0/200.0;
    }else{
        scaleFactor = imageSize.height*imageSize.height/200.0/200.0;
    }
    
    if (scaleFactor < 1.0) {
        qualityFactor = qualityFactor * sqrt(scaleFactor);
    }
    
    if (longerEdge / shorterEdge >= irregularFactor) {
        UIImage *zoomImage = [UIImage ty_imageScaleCut:self size:sizeForCut];
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:zoomImage forSize:zoomSize];
        NSData *newImageData =UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        return newImageData;
    }
    else if (longerEdge >= 200.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, qualityFactor);
        return newImageData;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, qualityFactor);
        return  newImageData;
    }
}

-(NSData *)ty_dataWithImageCompressForPanorama{
    CGSize  imageSize = self.size;
    CGFloat longerEdge;
    //    CGFloat shorterEdge;
    
    if (imageSize.height >= imageSize.width) {
        longerEdge = imageSize.height;
        //        shorterEdge = imageSize.width;
    }else{
        longerEdge = imageSize.width;
        //        shorterEdge = imageSize.height;
    }
    
    //    float qualityFactor = 0.75;
    CGSize sizeForScale = CGSizeMake(2048, 2048);
    //    float scaleFactor = 1.0;
    //
    //    if (imageSize.width > imageSize.height) {
    //        scaleFactor = imageSize.width*imageSize.width/2048/2048;
    //    }else{
    //        scaleFactor = imageSize.height*imageSize.height/2048/2048;
    //    }
    
    //    if (scaleFactor < 1.0) {
    //        qualityFactor = qualityFactor * sqrt(scaleFactor);
    //    }
    
    if (longerEdge >= 2048.0) {
        UIImage *newImageForScale = [UIImage ty_imageScaleWithSameProportion:self forSize:sizeForScale];
        NSData *newImageData = UIImageJPEGRepresentation(newImageForScale, 0.51);
        //UIImage *newImage = [UIImage imageWithData:newImageData];
        return newImageData;
    }else{
        NSData *newImageData =UIImageJPEGRepresentation(self, 0.51);
        //UIImage *newImage = [UIImage imageWithData:newImageData];
        return  newImageData;
    }
    
}

+ (UIImage *)ty_rotateImage:(UIImage *)image
                     byAngle:(CGFloat)angle {
    CGSize imgSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale);
    
    CGRect rect = CGRectMake(0, 0, imgSize.width, imgSize.height);
    rect = CGRectApplyAffineTransform(rect, CGAffineTransformMakeRotation(angle));
    CGSize outputSize = CGSizeMake(CGRectGetWidth(rect), CGRectGetHeight(rect));
    
    UIGraphicsBeginImageContext(outputSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextTranslateCTM(context, outputSize.width / 2, outputSize.height / 2);
    CGContextRotateCTM(context, angle);
    CGContextTranslateCTM(context, -imgSize.width / 2, -imgSize.height / 2);
    
    [image drawInRect:CGRectMake(0, 0, imgSize.width, imgSize.height)];
    
    UIImage *image1 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image1;
}

@end
